package com.tao.handler.security;

import com.alibaba.fastjson.JSON;

import com.tao.enums.AppHttpCodeEnum;
import com.tao.utils.WebUtils;
import com.tao.vo.ResponseResult;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 季伟
 * 功能：在进行用户认证的过程中如果发生异常，
 * springSecurity的异常处理类ExceptionTranslationFilter会调用这个类进行处理
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint{

    /**
     * 处理用户认证时发生的异常
     * @param request 发生异常的请求
     * @param response 响应回去的数据
     * @param authException 发生的认证异常
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        authException.printStackTrace();
        /*InsufficientAuthenticationException
         *缺少身份验证异常
         *访问需要权限的接口但没有携带token也就是在没有登录的状态下访问了权限接口
         * BadCredentialsException
         * 用户名或密码错误异常
         * 验证用户的密码不正确时
         */
        ResponseResult responseResult = null;
        if (authException instanceof InsufficientAuthenticationException){
            responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        }else if (authException instanceof BadCredentialsException){

            responseResult = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        }else {
            responseResult = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR,"用户认证失败");
        }
        String json = JSON.toJSONString(responseResult);
        //将json写入到response输出流中
        WebUtils.writeJsonDataToResponse(response,json);
    }
}
